package com.roger.ats.init.cases;

import android.content.ContentValues;
import android.database.Cursor;
import android.os.SystemClock;
import android.provider.CalendarContract;
import android.provider.CallLog;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiCollection;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.util.Log;

import com.roger.ats.init.util.CfgUtils;
import com.roger.ats.init.util.LogUtils;
import com.roger.uia.helper.UiBase;
import com.roger.uia.helper.manager.Package;
import com.roger.uia.helper.manager.Telephony;
import com.roger.uia.helper.util.StrUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

import static com.roger.uia.helper.UiBase.checkPoint;
import static com.roger.uia.helper.UiBase.existObj;
import static com.roger.uia.helper.UiBase.inputTxtToObj;
import static com.roger.uia.helper.UiBase.mDevice;
import static com.roger.uia.helper.UiBase.objSelect;
import static com.roger.uia.helper.UiBase.openApp;
import static com.roger.uia.helper.UiBase.waitClickObj;
import static com.roger.uia.helper.UiBase.waitObj;
import static com.roger.uia.helper.UiBase.waitObjCheck;
import static com.roger.uia.helper.UiBase.waitTime;

public class AppInit {
    private static final String TAG = "Test" + AppInit.class.getSimpleName();
    private static CfgUtils cfgUtils = new CfgUtils();
    private static LogUtils logUtils = new LogUtils();

    public static void disableApp(){
        logUtils.printLog("==start disable app==");
        String[] appList=cfgUtils.getPacInfo(UiBase.filePath+"ATS/config/blacklist.ini");
        for (String pac : appList){
            if(Package.pac().isAppInstalled(pac)) {
                try {
                    UiBase.disableApp(pac);
                    logUtils.printLog("disable app success : " + pac);
                } catch (Throwable e) {
                    logUtils.printLog("disable app fail : " + pac);
                }
            }
            else
                logUtils.printLog("not installed : " + pac );
        }
    }

    public static void grantApp(){
        logUtils.printLog("==start grant app==");
        String[] appList=cfgUtils.getPacInfo(UiBase.filePath+"ATS/config/whitelist.ini");
        for (String pac : appList){
            if(Package.pac().isAppInstalled(pac)) {
                try {
                    Package.pac().grantAllPerms(pac);
                    logUtils.printLog("grant app success : " + pac);
                } catch (Throwable e) {
                    logUtils.printLog("grant app fail : " + pac);
                }
            }
            else
                logUtils.printLog("not installed : " + pac );
        }
    }

    public static void closeAutoUpdate(){
        String pac = "com.android.vending";
        String menu = "com.android.vending:id/unauth_home_overflow";
        String btn = "com.android.vending:id/checkbox";
        mDevice.pressHome();
        logUtils.printLog("==start close auto update==");
        if(Package.pac().isAppInstalled(pac)){
            try {
                UiBase.openApp(pac);
                UiBase.waitClickObj(UiBase.objSelect[3],menu,10);
                UiBase.waitObjCheck(UiBase.objSelect[3],btn,3);
                if(UiBase.objChecked(UiBase.objSelect[3],btn))
                    UiBase.clickObj(UiBase.objSelect[3],btn);
                SystemClock.sleep(waitTime);
                UiBase.waitClickObj(UiBase.objSelect[3],menu,3);
                UiBase.checkPoint("check status",!UiBase.objChecked(UiBase.objSelect[3],btn));
                logUtils.printLog("close auto update success");
            } catch (Throwable e) {
                logUtils.printLog("close auto update fail");
            } finally {
                mDevice.pressBack();
                mDevice.pressHome();
            }
        }else{
            logUtils.printLog("not found Google Play");
        }
    }

    public static void openCalendar(){
        mDevice.pressHome();
        logUtils.printLog("==start open calendar==");
        String[] pac ={"com.google.android.calendar","com.android.calendar"};
        String arg = cfgUtils.getCfg("日历活动=");
        if(Package.pac().isAppInstalled(pac[0])){
            try {
                UiBase.forceStopApp(pac[0]);
                UiBase.openApp(pac[0]);
                UiBase.waitObj(UiBase.objSelect[4],"下一页",10);
                while (UiBase.existObj(UiBase.objSelect[4],"下一页")){
                    UiBase.clickObj(UiBase.objSelect[4],"下一页");
                    UiBase.waitObj(UiBase.objSelect[4],"下一页",3);
                }
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"知道了",3);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"关闭",3);
//                UiBase.waitClickObj(UiBase.objSelect[4],"创建新活动",3);
//                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"活动",3);
//                UiBase.waitObj(UiBase.objSelect[0],"添加标题",3);
//                UiBase.inputTxtToObj(UiBase.objSelect[0],"添加标题",arg);
//                //UiBase.clickObj(UiBase.objSelect[6],"开始日期.*");
//                UiBase.clickObj(UiBase.objSelect[2],".*年.*月.*日.*");
//                UiBase.waitClickObj(UiBase.objSelect[3],"android:id/date_picker_header_year",3);
//                UiBase.scrollReidClickObj("android:id/animator",UiBase.objSelect[0],"2019");
//                if(UiBase.existObj(UiBase.objSelect[2],"12月.*"))
//                    UiBase.waitClickObj(UiBase.objSelect[3],"android:id/prev",5);
//                UiBase.waitClickObj(UiBase.objSelect[6],".*01.*月.*",5);
//                UiBase.waitClickObj(UiBase.objSelect[0],"确定",5);
//                UiBase.waitClickObj(UiBase.objSelect[0],"保存",5);
                logUtils.printLog("open calendar success : " + pac[0]);
            } catch (Throwable e) {
                logUtils.printLog("open calendar fail : " + pac[0]);
            }
        }else if (Package.pac().isAppInstalled(pac[1])){
            try {
                UiBase.forceStopApp(pac[1]);
                UiBase.openApp(pac[1]);
                UiBase.waitClickObj(UiBase.objSelect[4],"更多选项",10);
                UiBase.waitClickObj(UiBase.objSelect[0],"设置",3);
                UiScrollable list = new UiScrollable(new UiSelector().resourceId("android:id/prefs_frame"));
                list.scrollIntoView(UiBase.getObj(UiBase.objSelect[2],"弹出式通知"));
                UiObject btn = UiBase.getObjSameLine(new UiCollection(new UiSelector().resourceId("android:id/prefs_frame")),UiBase.getObj(UiBase.objSelect[2],"弹出式通知"),UiBase.getObj(UiBase.objSelect[3],"android:id/checkbox"));
                if(!btn.isChecked())UiBase.clickObj(UiBase.objSelect[2],"弹出式通知");
//                UiBase.waitClickObj(UiBase.objSelect[0],"新建活动",3);
//                UiBase.waitObjCheck(UiBase.objSelect[0],"活动名称",3);
//                UiBase.inputTxtToObj(UiBase.objSelect[0],"活动名称",arg);
//                UiBase.waitClickObj(UiBase.objSelect[4],"开始日期",3);
//                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.calendar:id/date_picker_year",3);
//                UiBase.scrollReidClickObj("com.android.calendar:id/animator",UiBase.objSelect[5],"2019");
//                if(UiBase.existObj(UiBase.objSelect[6],".*十二月.*"))
//                    UiBase.getObj(UiBase.objSelect[3],"com.android.calendar:id/animator").swipeDown(100);
//                UiBase.waitClickObj(UiBase.objSelect[6],".*01.*月.*",5);
//                UiBase.waitClickObj(UiBase.objSelect[0],"完成",5);
//                UiBase.waitClickObj(UiBase.objSelect[0],"完成",5);
                logUtils.printLog("open calendar success : " + pac[1]);
            } catch (Throwable e) {
                logUtils.printLog("open calendar fail : " + pac[1]);
            }
        }else{
            logUtils.printLog("not find calendar");
        }
        mDevice.pressHome();
    }

    public static void openAppStore(){
        String pac = "com.lenovo.leos.appstore.pad";
        mDevice.pressHome();
        logUtils.printLog("==start open AppStore==");
        if(Package.pac().isAppInstalled(pac)){
            try {
                UiBase.openApp(pac);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"同意并继续",10);
                UiBase.waitObj(UiBase.objSelect[0],"以后不再弹出",10);
                if(UiBase.existObj(UiBase.objSelect[0],"以后不再弹出") && !UiBase.objChecked(UiBase.objSelect[0],"以后不再弹出")){
                    UiBase.clickObj(UiBase.objSelect[0],"以后不再弹出");
                }
                UiBase.clickObj(UiBase.objSelect[0],"进入首页");
                UiBase.waitObj(UiBase.objSelect[0],"我的",10);
                UiBase.checkPoint("check status",UiBase.existObj(UiBase.objSelect[0],"我的"));
                logUtils.printLog("open app success : " + pac);
            } catch (Throwable e) {
                logUtils.printLog("open app fail : " + pac);
            }
        }else{
            logUtils.printLog("not installed : " + pac);
        }
        mDevice.pressHome();
    }

    public static void openSoundRecorder(){
        String pac = "com.tblenovo.soundrecorder";
        mDevice.pressHome();
        logUtils.printLog("==start open SoundRecorder==");
        if(Package.pac().isAppInstalled(pac)){
            try {
                UiBase.openApp(pac);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"同意并继续",10);
                UiBase.waitObjCheck(UiBase.objSelect[4],"录音列表",10);
                logUtils.printLog("open app success : " + pac);
            } catch (Throwable e) {
                logUtils.printLog("open app fail : " + pac);
            }
        }else{
            logUtils.printLog("not installed : " + pac);
        }
        mDevice.pressHome();
    }

    public static void openNBUFiles(){
        String pac = "com.google.android.apps.nbu.files";
        mDevice.pressHome();
        logUtils.printLog("==start open nbu files==");
        if(Package.pac().isAppInstalled(pac)){
            try {
                UiBase.openApp(pac);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"继续",10);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"同意并继续",10);
                UiBase.waitObjCheck(UiBase.objSelect[0],"文件极客",10);
                UiBase.waitClickObj(UiBase.objSelect[4],"显示导航菜单",3);
                UiBase.waitClickObj(UiBase.objSelect[0],"设置",3);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"更新设置",3);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"不自动更新",3);
                logUtils.printLog("open app success : " + pac);
            } catch (Throwable e) {
                logUtils.printLog("open app fail : " + pac);
            }
        }else{
            logUtils.printLog("not installed : " + pac);
        }
        mDevice.pressHome();
    }

    public static void openChrome() {
        String row_chrome = "com.android.chrome";
        String prc_browser = "com.lenovo.browser";
        UiObject baidu_mark = mDevice.findObject(new UiSelector().textMatches("百度一下"));
        UiScrollable bookmarklist = new UiScrollable(new UiSelector().resourceId("com.android.chrome:id/recycler_view"));

        mDevice.pressHome();
        logUtils.printLog("==start open chrome==");
        if (Package.pac().isAppInstalled(row_chrome)) {
            try {
                UiBase.openApp(row_chrome);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"接受并继续",10);
                UiBase.waitClickIfObjExist(UiBase.objSelect[0],"不用了，谢谢",10);
                UiBase.waitClickObj(UiBase.objSelect[3],"com.android.chrome:id/url_bar",5);
                inputTxtToObj(objSelect[3], "com.android.chrome:id/url_bar", "www.baidu.com");
                mDevice.pressEnter();
                waitObjCheck(objSelect[0], "m.baidu.com/?from=844b&vit=fps", 10);
                waitClickObj(objSelect[3], "com.android.chrome:id/bookmark_button", 3);
                if (existObj(objSelect[0], "修改书签")) {
                    logUtils.printLog("baidu bookmark already exist");
                    mDevice.pressHome();
                    return;
                }
                mDevice.pressBack();
                waitClickObj(objSelect[3], "com.android.chrome:id/menu_button", 3);
                waitClickObj(objSelect[0], "书签", 3);
                bookmarklist.scrollIntoView(baidu_mark);
                checkPoint("check status", existObj(objSelect[0], "百度一下"));
                logUtils.printLog("add baidu bookmark success: " + row_chrome);
            } catch (Throwable e) {
                logUtils.printLog("add baidu bookmark fail: " + row_chrome);
            }
        }else{
            logUtils.printLog("not installed : " + row_chrome);
        }
        mDevice.pressHome();
    }

    public static void addCallLogs(){
        if(!Telephony.tel().isLTE()) return;
        String num = cfgUtils.getCfg("call_log=");
        ContentValues values = new ContentValues();
        values.clear();
        values.put(CallLog.Calls.CACHED_NAME, "");
        values.put(CallLog.Calls.NUMBER, num);
        values.put(CallLog.Calls.TYPE, 1);
        values.put(CallLog.Calls.DATE,System.currentTimeMillis());
        values.put(CallLog.Calls.DURATION, "");
        values.put(CallLog.Calls.NEW, "0");
        InstrumentationRegistry.getTargetContext().getContentResolver().insert(CallLog.Calls.CONTENT_URI, values);
    }

    public static void addCalendarEvent(){
        String arg = cfgUtils.getCfg("calendar_activity=");
        String date = cfgUtils.getCfg("calendar_activity_date=");
        SimpleDateFormat sdf = new SimpleDateFormat ("yyyy/MM/dd", Locale.CHINA);
        long time;
        try {
            time = sdf.parse(date).getTime() + 36000000L;
        } catch (ParseException e) {
            time = 1572602400000L;
        }
        if(!CalendarEvent(arg)){
            //Calendar calendar = Calendar.getInstance();
            //long startMillis = calendar.getTimeInMillis();
            ContentValues values = new ContentValues();
            values.clear();
            values.put(CalendarContract.Events.DTSTART, time);//2019/11/01 18:00:00.000
            values.put(CalendarContract.Events.DTEND,time);
            values.put(CalendarContract.Events.TITLE, arg);
            values.put(CalendarContract.Events.CALENDAR_ID, 1);
            values.put(CalendarContract.Events.ALL_DAY, 1);
            values.put(CalendarContract.Events.EVENT_TIMEZONE, TimeZone.getDefault().getID());
            InstrumentationRegistry.getTargetContext().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, values);
        }

    }

    private static Boolean CalendarEvent(String s) {
        try (Cursor c = InstrumentationRegistry.getTargetContext().getContentResolver().query(CalendarContract.Events.CONTENT_URI, null, null, null, null)) {
            if (c == null) return false;
            int count = c.getCount();
            if (count > 0) {
                c.moveToNext();
                if(c.getString(c.getColumnIndex(CalendarContract.Events.TITLE)).equals(s)) return true;
            }
        }
        return false;
    }

    public static void addMapHistory() {
//        add map search history
        String map = "com.google.android.apps.maps";
        String search_edit_box = "com.google.android.apps.maps:id/search_omnibox_edit_text";
        mDevice.pressHome();
        logUtils.printLog("==start add map search history==");
        for (int i = 0; i <= 3; i++) {
            try {
                if (Package.pac().isAppInstalled(map)) {
                    openApp(map);
                    waitObj(objSelect[3], "com.google.android.apps.maps:id/home_bottom_sheet_container", 5);
                    waitClickObj(objSelect[0], "Search here", 5);
                    if (existObj(objSelect[1], "火车站")) {
                        logUtils.printLog("map search history already exist");
                        break;
                    }
                    inputTxtToObj(objSelect[3], search_edit_box, "火车站");
                    waitClickObj(objSelect[1], "火车站", 5);
                    waitClickObj(objSelect[3], "com.google.android.apps.maps:id/search_omnibox_text_clear", 5);
                    waitClickObj(objSelect[0], "Search here", 5);
                    checkPoint("check status", existObj(objSelect[1], "火车站"));
                    logUtils.printLog("add map search history success");
                    break;
                } else {
                    logUtils.printLog("no ROW");
                    break;
                }
            } catch (Throwable e) {
                logUtils.printLog("add map search history fail");
            }finally {
                mDevice.pressHome();
            }

        }

    }


}
